import { message, notification } from "ant-design-vue";
import axios, { AxiosInstance } from "axios";

// import VueAxios from 'vue-axios';
// import store from '@/store'
import CooieTool from "@/utils/cookie";

import errorCode from "./errorCode";

// 异常拦截处理器
const errorHandler = (error: any) => {
	let { message } = error;
	if (message === "Network Error") {
		message = "后端接口连接异常";
	} else if (message.includes("timeout")) {
		message = "系统接口请求超时";
	} else if (message.includes("Request failed with status code")) {
		message = "系统接口" + message.substr(message.length - 3) + "异常";
	}
	// message.error(message, 3);

	notification.error({
		message: message,
		duration: 5 * 1000
	});
	//  return Promise.reject(error) //注释该行，否则接口请求失败会一直请求刷新错误数据，这里保证请求一次
};
const request = axios.create({
	// API 请求的默认前缀
	baseURL: process.env.API_HTTP,
	// baseURL: import.meta.env.VITE_BASE_URL, //vite自身环境变量,根据运行打包环境切换，
	timeout: 20000, // 请求超时时间
	withCredentials: true
});
// request interceptor
request.interceptors.request.use(config => {
	const token = CooieTool.getCookie("Cusertoken");
	config.headers = {
		"Content-Type": "application/json"
	} as any ;//as any 只是为了保证当前代码不报错，缺少很多属性
	const isToken = (config.headers || {}).isToken === false;
	if (token && !isToken) {
		// config.headers['SysSubCode'] = store.state.settings.name
		config.headers["Authorization"] = `Bearer ${token}`;
	}
	// get请求映射params参数
	if (config.method === "get" && config.params) {
		let url = config.url + "?";
		for (const propName of Object.keys(config.params)) {
			const value = config.params[propName];
			var part = encodeURIComponent(propName) + "=";
			// 修改漏洞
			if (value != null && typeof value !== "undefined") {
				if (typeof value === "object") {
					for (const key of Object.keys(value)) {
						const params = propName + "[" + key + "]";
						var subPart = encodeURIComponent(params) + "=";
						url += subPart + encodeURIComponent(value[key]) + "&";
					}
				} else {
					url += part + encodeURIComponent(value) + "&";
				}
			}
		}
		url = url.slice(0, -1);
		config.params = {};
		config.url = url;
	}
	return config;
}, errorHandler);
// response interceptor
request.interceptors.response.use(res => {
	if (res.headers?.date) (window as any).serverDateStr = res.headers.date;
	// 请求rul
	const requestUrl = res.config.url;
	// 未设置状态码则默认成功状态
	const code = res.data.code || 200;
	// 获取错误信息
	const msg = (errorCode as any)[code] || res.data.msg || errorCode["default"];
	if (code === 401) {
		message.error(msg, 3);
		// notification.open({
		// 	key: "loginExpireTip",
		// 	message: "系统提示",
		// 	description: "登录状态已过期，请重新登录"
		// });
	} else if (code === 500) {
		if (requestUrl !== "/login" && requestUrl !== "/logout") {
			message.error(msg, 3);
		} else {
			message.error(msg, 3);
			// notification.error({
			//   message: msg,
			//   description: msg,
			// });
			return res.data;
		}
	} else if (code !== 200 && requestUrl !== "/logout") {
		message.error(msg, 3);
		// notification.error({
		//   message: msg,
		// });
	} else {
		if (res.data && res.data instanceof Object) res.data.success = true;
		return res.data;
	}
	return Promise.reject(msg);
}, errorHandler);
// const installer = {
//     vm: {},
//     install(Vue: { use: (arg0: any, arg1: AxiosInstance) => void }) {
//         Vue.use(VueAxios, request);
//     },
// };
export default request;
(request as any).headers = function () {
	const token = CooieTool.getCookie("Cusertoken");
	return { Authorization: "Bearer " + token };
};

// export { installer as VueAxios, request as axios };
